package tbdp.tool.core.spi.processor;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import tbdp.tool.common.JobConstants;
import tbdp.tool.common.StockInfo;
import tbdp.tool.config.JobConfig;
import tbdp.tool.config.ProcessorConfig;
import tbdp.tool.context.JobContext;
import tbdp.tool.core.db.DBUtil;
import tbdp.tool.core.spi.processor.sql.DataSource;
import tbdp.tool.datasource.DataSourceConfig;
import tbdp.tool.datasource.DataSourceConfigFactory;
import tbdp.tool.spi.Processor;
import tbdp.tool.util.BeanCovertUtil;

/**
 * sql 处理器
 *
 * @author xbkaishui
 * @version $Id: SqlProcessor.java, v 0.1 2017-06-17 下午4:28 xbkaishui Exp $$
 */
public class SqlProcessor extends Processor {
    @Override
    public String getType() {
        return "sql";
    }

    @Override
    public void process(JobContext context, ProcessorConfig processorConfig) {
        String sql = processorConfig.getConfigPropAsString(JobConstants.SQL);
        try {
            List<Object> result = evalSql(sql, processorConfig);
            context.put(JobConstants.STOCK_LIST, result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 运行sql 获取数据
     * @param sql
     * @param processorConfig
     * @return
     * @throws IOException
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    private List<Object> evalSql(String sql, ProcessorConfig processorConfig) throws IOException, SQLException, ClassNotFoundException {
        String dataSource = processorConfig.getConfigPropAsString(JobConstants.DATASOURCE);
        String beanClass = processorConfig.getConfigPropAsString(JobConstants.BEAN_CLASS, StockInfo.class.getCanonicalName());
        Class clazz = Class.forName(beanClass);
        DataSourceConfig dataSourceConfig = DataSourceConfigFactory.getDataSourceConfig(dataSource);
        logger.info("dataSourceConfig {} ", dataSourceConfig);
        Connection conn = DataSource.getConnection(dataSourceConfig);
        ResultSet rs = DBUtil.query(conn, sql);
        List<Object> stockList = new LinkedList();
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount(); //Map rowData;
        while (rs.next()) {
            Map<String, Object> rowData = new HashMap<String, Object>();
            //获取 as 标签
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnLabel(i), rs.getObject(i));
            }
            Object obj = BeanCovertUtil.beanCovert(rowData, clazz);
            stockList.add(obj);
        }
        return stockList;
    }

    @Override
    public boolean needHandle(JobConfig jobConfig) {
        return true;
    }
}
